<template>
  <div class="panel environment-data">
    <h2 class="panel-title">
      <DataAnalysis class="el-icon" />
      环境数据
    </h2>
    <div class="data-grid">
      <div class="data-card">
        <Sunny class="el-icon" />
        <div class="data-value">{{ latestData.airTemperature?.value || '--' }}°C</div>
        <div class="data-label">空气温度</div>
      </div>
      <div class="data-card">
        <Cloudy class="el-icon" />
        <div class="data-value">{{ latestData.soilMoisture?.value || '--' }}%</div>
        <div class="data-label">土壤湿度</div>
      </div>
      <div class="data-card">
        <Lightning class="el-icon" />
        <div class="data-value">{{ latestData.soilTemperature?.value || '--' }}°C</div>
        <div class="data-label">土壤温度</div>
      </div>
      <div class="data-card">
        <Umbrella class="el-icon" />
        <div class="data-value">{{ latestData.soilNitrogen?.value || '--' }}mg/kg</div>
        <div class="data-label">土壤氮含量</div>
      </div>
      <div class="data-card">
        <WindPower class="el-icon" />
        <div class="data-value">{{ latestData.carbonDioxide?.value || '--' }}ppm</div>
        <div class="data-label">二氧化碳</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { DataAnalysis, Sunny, Cloudy, Lightning, Umbrella, WindPower } from '@element-plus/icons-vue'
import axios from 'axios'

const latestData = ref({})
let timer

const fetchLatestData = async () => {
  try {
    const response = await axios.get('/api/sensors/latest')
    latestData.value = response.data
  } catch (error) {
    console.error('获取最新数据失败:', error)
  }
}

onMounted(() => {
  fetchLatestData()
  timer = setInterval(fetchLatestData, 60000) // 每分钟更新一次
})

onUnmounted(() => {
  clearInterval(timer)
})
</script>

<style scoped>
.environment-data {
  height: 300px;
}

.data-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px;
  padding: 15px;
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.data-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  background: rgba(66, 185, 131, 0.1);
  border: 1px solid #42b983;
  border-radius: 4px;
  padding: 15px;
}

.el-icon {
  font-size: 24px;
  color: #42b983;
}

.data-value {
  font-size: 20px;
  color: #42b983;
}

.data-label {
  font-size: 12px;
  color: #888;
}
</style> 